<template>
  <div class="login-page">
    <van-nav-bar left-arrow  @click-left="onClickLeft" />
    <div class="wrapper">
      <h3>短信登录</h3>
      <van-form @submit="onSubmit" ref="form">
        <van-field
        v-model.number="mobile"
          name="mobile"
          label=""
          placeholder="请输入手机号"
          :rules="[{ pattern:/^(?:(?:\+|00)86)?1[3-9]\d{9}$/ ,message: '请输入正确的手机号' }]"
        />
        <div class="code">
          <van-field
          v-model="code"
            type="text"
            name="code"
            label=""
            placeholder="请输入验证码"
            :rules="[{ pattern:/^\d{6}$/, message: '验证码6位数字' }]"
          />
          <span class="msg-btn" @click="getcode" native-type="button">   {{second===0?'发送验证码':`${second}秒后发送`}} </span>
        </div>
        <div style="margin: 16px">
          <van-button round block type="info" native-type="submit"
            >登 录</van-button
          >
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import to from 'await-to-js'
import { mobile, login } from '@/api/user'
import { Toast } from 'vant'
import { setToken } from '@/utils/storage'
export default {
  name: 'LoginPage',
  data () {
    return {
      mobile: '',
      code: '',
      second: 0,
      timer: ''
    }
  },
  methods: {
    async onSubmit (values) {
      const [err, res] = await to(login({
        mobile: this.mobile,
        code: this.code
      }))
      if (err) return Toast.fail(err.response.data.message)
      else {
        Toast.success('登录成功')
        setToken(res.data.data.token)
        this.$router.push('/')
      }
    },
    onClickLeft () {
      this.$router.back()
    },
    async getcode () {
      if (this.second > 0) return
      const [unPass] = await to(this.$refs.form.validate('mobile'))
      if (unPass) return
      const [err] = await to(mobile(this.mobile))
      if (err) return Toast.fail('发送失败')
      this.second = 60
      if (this.timer) clearInterval(this.timer)
      this.timer = setInterval(() => {
        this.second--
        if (this.second <= 0) clearInterval(this.timer)
      }, 1000)
    }
  }
}
</script>

<style scoped lang="less">
.wrapper {
  padding: 0 30px;
  .van-form {
    padding: 30px 0;
    .van-button {
      background: linear-gradient(90deg, #fe4f4f, #fc6627);
      border-radius: 0;
      border: none;
    }
  }
}
h3 {
  font-size: 23px;
  font-weight: normal;
}
.code {
  display: flex;
  .van-cell{
    flex:1;
  }
  .msg-btn{
    color: #999;
    font-size: 12px;
    width: 67px;
    line-height: 44px;
  }
}
.van-cell{
    padding: 20px;
}
</style>
